package cn.youyeku.zsxh.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import cn.youyeku.zsxh.Utils.LogUtils;


/**
 * Created by wings on 2016/12/20.
 */

public class YeDBConnect {
    private YeDBHelper yeDBHelper;
    private SQLiteDatabase db;

    static final String DB_NAME = "YeDatabase.db";
    static final int VERSION = 1;
    static YeDBConnect yeDBConnect = null;

    //对应单例模式
    private YeDBConnect(Context mContext, char mode) {
        yeDBHelper = new YeDBHelper(mContext, DB_NAME, null, VERSION);
        switchMode(mode);
    }

    /*参数 数据库名称 默认模式为 写模式 w 写 r 读取*/
    private YeDBConnect(Context mContext, char mode, String dbFileName, int version) {
        yeDBHelper = new YeDBHelper(mContext, dbFileName, null, version);
        switchMode(mode);
    }

    private void switchMode(char mode) {
        switch (mode) {
            case 'w':
                this.db = yeDBHelper.getWritableDatabase();
                break;
            case 'r':
                this.db = yeDBHelper.getReadableDatabase();
                break;
            default:
                this.db = yeDBHelper.getWritableDatabase();
        }
    }

    //static synchronized方法也相当于全局锁，相当于锁住了代码段
    //synchronized锁住的是括号里的对象，而不是代码。对于非static的synchronized方法，锁的就是对象本身也就是this。
    public static synchronized YeDBConnect getInstance(Context context, char mode) {
        if (yeDBConnect == null) {
            yeDBConnect = new YeDBConnect(context, mode, DB_NAME, VERSION);
        }
        return yeDBConnect;
    }


    /**
     * @param sql I dont't know it will be null or not ...
     */
    public void createTable(String sql) {

        this.db.execSQL(sql);
    }

    public void insertMany(String sql) {

    }

    public void execute(String sql) {
        this.db.execSQL(sql);
    }

    public String query(String number) {
        number = "%" + number + "%";
        Cursor cursor = this.db.rawQuery("select * from message where phone like ? ", new String[]{number});
        String tmp = "";
        while (cursor.moveToNext()) {
            tmp += String.format("%s %s %s %s", cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getInt(3)) + "\n";
        }
        cursor.close();
        return tmp;

    }

    public Cursor executeFetchData(String sql) {

        LogUtils.w(sql);
       return db.rawQuery(sql,null);

    }
}


